package cn.codecang.mall.common.interceptor;

import cn.codecang.mall.common.consts.ErrorCode;
import cn.codecang.mall.common.response.Result;
import cn.codecang.mall.common.utils.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TokenInterceptor
 *
 * @author xiaoluo
 * @date 2023/6/3 14:25
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        //跨域请求会首先发一个option请求，直接返回正常状态并通过拦截器
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //判断如果请求的类是swagger的控制器，直接通行。
        if (handlerMethod.getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")) {
            return true;
        }
        String token = request.getHeader("token");
        try {
            if (token != null) {
                DecodedJWT decode = JWTUtil.decodeToken(token);
                if (decode != null) {
                    log.info("验证通过");
                    return true;
                }
            }

            Result<Object> error = Result.error(ErrorCode.TOKEN_VERIFY);
            String json = JSON.toJSONString(error);

            //让浏览器用utf8来解析返回的数据
            response.setContentType("application/json;charset=UTF-8");
            //告知servlet用UTF-8转码，而不是用默认的ISO-8859-1,并且这一行代码尽可能的放在代码段的上面，否则可能会无效
            response.setCharacterEncoding("UTF-8");

            response.getWriter().append(json);
        } catch (Exception e) {
            return false;
        }
        return false;
    }
}
